<template>
  <div
    ref="rightPanelRef"
    :class="{show:show}"
    class="rightPanel-container"
  >
    <div class="rightPanel-background" />
    <div class="rightPanel">
      <div
        class="handle-button"
        :style="{'top':buttonTop+'px','background-color':theme}"
        @click="show=!show"
      >
        <el-icon v-if="show">
          <Close />
        </el-icon>
        <el-icon v-else>
          <Setting />
        </el-icon>
      </div>
      <div class="rightPanel-items">
        <slot />
      </div>
    </div>
  </div>
</template>

<script setup>
import { addClass, removeClass } from '@/utils/index.js'

const props = defineProps({
  clickNotClose: {
    default: false,
    type: Boolean
  },
  buttonTop: {
    default: 250,
    type: Number
  }
})

const show = ref(false)
const theme = ref('#000')

watch(() => show.value, (value) => {
  if (value && !props.clickNotClose) {
    addEventClick()
  }
  if (value) {
    addClass(document.body, 'showRightPanel')
  } else {
    removeClass(document.body, 'showRightPanel')
  }
})

onMounted(() => {
  insertToBody()
})

const rightPanelRef = ref(null)
onBeforeUnmount(() => {
  rightPanelRef.value.remove()
})

const addEventClick = () => {
  window.addEventListener('click', closeSidebar)
}

const closeSidebar = (evt) => {
  const parent = evt.target.closest('.rightPanel')
  if (!parent) {
    show.value = false
    window.removeEventListener('click', closeSidebar)
  }
}

const insertToBody = () => {
  const elx = rightPanelRef.value
  const body = document.querySelector('body')
  body.insertBefore(elx, body.firstChild)
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
